﻿using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web.Mvc;
using doufu.Common;

namespace doufu.WebUI.Controllers
{
    public class CommController : BaseController
    {
        #region Upload
        public ActionResult Upload(string dir)
        {
            //定义允许上传的文件扩展名
            var extTable = new Hashtable
                               {
                                   {"image", "gif,jpg,jpeg,png,bmp"},
                                   {"flash", "swf,flv"},
                                   {"media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"},
                                   {"file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"}
                               };

            //最大文件大小
            int maxSize = int.Parse(System.Configuration.ConfigurationManager.AppSettings["UploadMaxLimit"] ?? "524288");//524288=512k
            //文件保存目录路径
            const string savePath = "/attached/";
            var imgFile = Request.Files["imgFile"];
            if (imgFile == null)
            {
                return showError("请选择文件。");
            }

            #region MyRegion
            string dirName = dir;
            if (String.IsNullOrEmpty(dirName))
            {
                dirName = "image";
            }
            if (!extTable.ContainsKey(dirName))
            {
                return showError("目录名不正确。");
            }
            String fileName = imgFile.FileName;
            String fileExt = Path.GetExtension(fileName).ToLower();
            if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
            {
                return showError("上传文件大小超过限制。");
            }
            if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                return showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。");
            }
            #endregion

            //创建文件夹
            string filePath = string.Format("{0}{1}/{2}/{3}{4}", savePath, dirName, DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo),
                DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo), fileExt
                );
            var fileSavePath = Server.MapPath(filePath);
            var fileSaveDir = Path.GetDirectoryName(fileSavePath) ?? string.Empty;
            if (!Directory.Exists(fileSaveDir))
            {
                Directory.CreateDirectory(fileSaveDir);
            }
            imgFile.SaveAs(fileSavePath);

            return Json(new { error = 0, url = filePath });
        }

        private ActionResult showError(string message)
        {
            return Json(new { error = 1, message });
        }
        #endregion

        #region CSS
        //[OutputCache(Duration = 600)]
        public ActionResult GetCSS(string css)
        {
            var csscontent = new StringBuilder("<style type=\"text/css\"> ");
            csscontent.Append(LoadFile.Load(Server.MapPath("~/Content/Style/comm.css")));
            if (!string.IsNullOrEmpty(css))
            {
                string[] s = css.Split(',');
                foreach (var s1 in s)
                {
                    csscontent.Append(" ");
                    csscontent.Append(LoadFile.Load(Server.MapPath(string.Format("~/Content/Style/{0}", s1))));
                    csscontent.Append(" ");
                }
            }
            csscontent.Append("</style>");
            return Content(csscontent.Replace("\r\n", "").Replace("\t", "").Replace("  ", "").ToString());
            //return Content(csscontent.ToString());
        }
        #endregion

        public ActionResult PageNotFind()
        {
            return RedirectToAction("Index", "Home");
        }
    }
}
